package dao;

import java.util.List;

import model.Company;
import model.Product;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

public class productDAO {

	/**
	 * Session.
	 */
	private Session session;
	private companyDAO comDAO = new companyDAO();

	public productDAO() {
		this.session = HibernateUtil.getSessionFactory().openSession();
	}

	public boolean addProduct(Product product) {
		try {
			session.beginTransaction();
			session.save(product);
			session.getTransaction().commit();
			return true;
		} catch (HibernateException e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			e.printStackTrace();
		} finally {
			if(session!=null)
				session.close();
		}
		return false;
	}

	public boolean updateProduct(Product product) {
		try {
			session.beginTransaction();
			session.update(product);
			session.getTransaction().commit();
			return true;
		} catch (HibernateException e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			e.printStackTrace();
		} finally {
			if(session!=null)
				session.close();;
		}
		return false;
	}

	public Product getProductByID(int productId) {
		Product product = null;
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			product = (Product) session.get(Product.class, productId);
			session.getTransaction().commit();
			return product;
		} catch (HibernateException e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			e.printStackTrace();
		} finally {
			if(session!=null)
				session.close();
		}
		return product;
	}

	@SuppressWarnings("unchecked")
	public final List<Product> getListProductByCompanyID(int comID) {
		Company company = comDAO.getCompanyById(comID);
		List<Product> ds = null;
		try {
			session.beginTransaction();
			Criteria cri = session.createCriteria(Product.class).add(
					Restrictions.eq("company",company)).add(Restrictions.eq("isActive", true));
			ds = cri.list();
			session.getTransaction().commit();
		} catch (HibernateException ex) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			ex.printStackTrace();
		} finally {
			if(session!=null)
				session.close();
		}
		return ds;
	}

}
